package com.hzzc.sso.sdk.session;

import com.hzzc.sso.sdk.SsoWebSdkProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class SessionManager implements InitializingBean {

    public static final ThreadLocal<String> localCode = new ThreadLocal<String>();

    @Autowired
    private SsoWebSdkProperties ssoWebSdkProperties;

    private Map<String, SsoSession> sessionsMap = new ConcurrentHashMap();

    public HttpSession getSession(String sessionId) {
        if (StringUtils.isEmpty(sessionId)) {
            return new SsoSession("default");
        }
        synchronized (sessionId) {
            SsoSession ssoSession = sessionsMap.get(sessionId);
            if (ssoSession == null || ssoSession.isExpired(ssoWebSdkProperties.getSessionDuration())) {
                ssoSession = new SsoSession(sessionId);
                sessionsMap.put(sessionId, ssoSession);
            }
            ssoSession.updateLastAccessTime();
            return ssoSession;
        }
    }

    public void setLocalCode(String code) {
        SessionManager.localCode.set(code);
    }

    public String getLocalCode() {
        return SessionManager.localCode.get();
    }

    public void removeLocalCode() {
        SessionManager.localCode.remove();
    }

    public void cleanSession(String sessionId) {
        sessionsMap.remove(sessionId);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        new SessionExpireChecker(ssoWebSdkProperties.getSessionDuration(), sessionsMap).start();
        log.info("##Session超时检测线程启动成功！");
    }

}
